// 通用数据管理Hook
function useDataManagement(apiEndpoint, mockData = []) {
    const [data, setData] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [searchTerm, setSearchTerm] = React.useState('');
    const [currentPage, setCurrentPage] = React.useState(1);
    const [itemsPerPage, setItemsPerPage] = React.useState(10);
    const [totalCount, setTotalCount] = React.useState(0);
    const [error, setError] = React.useState(null);

    // 获取数据的通用方法
    const fetchData = async (page = 1, search = '') => {
        setLoading(true);
        setError(null);
        
        try {
            const url = `${apiEndpoint}?page=${page}&size=${itemsPerPage}&search=${encodeURIComponent(search)}`;
            const result = await Utils.fetchData(Utils.getApiUrl(url));
            
            if (result && result.status === 0) {
                setData(result.data.rows || []);
                setTotalCount(result.data.count || 0);
            } else {
                // 使用模拟数据
                const filteredData = mockData.filter(item => 
                    !search || 
                    Object.values(item).some(value => 
                        String(value).toLowerCase().includes(search.toLowerCase())
                    )
                );
                setData(filteredData);
                setTotalCount(filteredData.length);
            }
        } catch (error) {
            console.error('获取数据失败:', error);
            setError(error.message);
            
            // 使用模拟数据作为后备
            const filteredData = mockData.filter(item => 
                !search || 
                Object.values(item).some(value => 
                    String(value).toLowerCase().includes(search.toLowerCase())
                )
            );
            setData(filteredData);
            setTotalCount(filteredData.length);
        } finally {
            setLoading(false);
        }
    };

    // 搜索处理
    const handleSearch = (e) => {
        setSearchTerm(e.target.value);
        setCurrentPage(1);
    };

    // 分页处理
    const handlePageChange = (page) => {
        setCurrentPage(page);
    };

    // 每页数量处理
    const handleItemsPerPageChange = (newItemsPerPage) => {
        setItemsPerPage(newItemsPerPage);
        setCurrentPage(1);
    };

    // 计算总页数
    const totalPages = Math.ceil(totalCount / itemsPerPage);

    // 组件挂载时获取数据
    React.useEffect(() => {
        fetchData(currentPage, searchTerm);
    }, [currentPage, searchTerm, itemsPerPage]);

    return {
        data,
        loading,
        error,
        searchTerm,
        currentPage,
        itemsPerPage,
        totalCount,
        totalPages,
        handleSearch,
        handlePageChange,
        handleItemsPerPageChange,
        fetchData
    };
}

// 注册到全局作用域
window.useDataManagement = useDataManagement;